//
//  AppDelegate.m
//  SmartHome
//
//  Created by 赵嘉诚 on 15/3/12.
//  Copyright (c) 2015年 赵嘉诚. All rights reserved.
//

#import "AppDelegate.h"
#import "startView.h"
#import "registView.h"
#import "ViewController.h"
#import "SSZipArchive.h"

@interface AppDelegate () <GCDAsyncSocketDelegate, startViewDelegate>
{
    NSString *serverIP;
    NSInteger port;
    NSString *serverID;
    NSMutableData *jsonData;
    NSDictionary *jsonDic;
    int fileLength;
    BOOL isUpdata;
    UIView *connectView;
    UIView *updateView;
    UILabel *remainLabel;
    NSTimer *connectTimer;
    NSTimer *remainTimer;
    BOOL isReConnect;
    BOOL isSended;
    NSString *messagePrefix;
}

@property (nonatomic, strong) startView *myStartView;
@property (nonatomic, strong) registView *myRegisterView;
@property (nonatomic, strong) ViewController *myViewController;

@end

@implementation AppDelegate

- (startView *)myStartView
{
    if(!_myStartView){
        _myStartView = [[startView alloc] initWithNibName:nil bundle:nil];
        _myStartView.delegate = self;
    }
    return _myStartView;
}

- (registView *)myRegisterView
{
    if(!_myRegisterView){
        _myRegisterView = [[registView alloc] initWithNibName:nil bundle:nil];
    }
    return _myRegisterView;
}

- (ViewController *)myViewController
{
    if(!_myViewController){
        _myViewController = [[ViewController alloc] initWithNibName:nil bundle:nil andDic:jsonDic];
        
        __weak AppDelegate *appD = self;
        _myViewController.sendMessage = ^(NSString *message1, NSString *message2){
            [appD sendMessgae1:message1 message2:message2];
        };
        _myViewController.sendFullMessage = ^(NSString *message){
            [appD sendFullMessage:message];
        };
    }
    return _myViewController;
}


//获得json文件数据
- (void)getJsonDic
{
    //是否有TXT文件
    NSString *jsonPath = [NSHomeDirectory() stringByAppendingPathComponent:TXT_FILE_NAME];
    NSData *fileData = [NSData dataWithContentsOfFile:jsonPath];
    
    if(!fileData || isUpdata){
        if(isUpdata){
            NSLog(@"文件有更新，重新解压");
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:jsonPath error:nil];
            NSLog(@"删除文件");
            fileData = nil;
        }else{
            NSLog(@"无txt文件，需要解压");
        }
        //解压
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:DOCUMENTS];
        NSString *zipPath = [NSHomeDirectory() stringByAppendingPathComponent:CMD_FILE_NAME];
        NSData *zipData = [NSData dataWithContentsOfFile:zipPath];
        if(!zipData){
            NSLog(@"错误，无压缩文件");
            return;
        }
        NSLog(@"解压文件");
        [SSZipArchive unzipFileAtPath:zipPath toDestination:path];
        //json 文件
        jsonPath = [NSHomeDirectory() stringByAppendingPathComponent:TXT_FILE_NAME];
        fileData = [NSData dataWithContentsOfFile:jsonPath];
        NSLog(@"解压成功");
    }
    NSLog(@"读取txt");
    
    NSDictionary *dic;
    dic = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingAllowFragments error:nil];
    if(!jsonDic){
        jsonDic = [[NSDictionary alloc] initWithDictionary:dic];
    }
}

// startViewDelegate 协议
- (void)loadServerWithEnitity:(Entity *)entity andIsUpdata:(BOOL)isUpdataFile
{
//    dispatch_queue_t myQueue = dispatch_queue_create("myque", NULL);
    asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    isUpdata = isUpdataFile;
    serverIP = entity.ip;
    port = [entity.port integerValue];
    serverID = entity.serverId;
    //[self showUpdateView];
    //[self showConnectView];
    [self skipMainView];
}

//显示连接服务器的提示画面
- (void)showConnectView
{
    [self.myStartView removeTableView];
    if(connectView != nil){
        [connectView removeFromSuperview];
    }
    NSLog(@"%@,%ld,%@",serverIP,(long)port,serverID);
    NSError *err = nil;
    [asyncSocket connectToHost:serverIP onPort:port error:&err];
    NSLog(@"尝试连接");
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    view.center = CGPointMake(self.myStartView.view.bounds.size.width / 2, self.myStartView.view.bounds.size.height / 2);
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.8;
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.center = CGPointMake(view.bounds.size.width / 2, view.bounds.size.height / 3);
    [view addSubview:activityView];
    [activityView startAnimating];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 100, 20)];
    label.text = @"正在连接";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [view addSubview:label];
    
    connectView = view;
    [self.myStartView.view addSubview:view];
    connectTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(noConnect) userInfo:nil repeats:NO];  //定时器
}

//显示更新文件的提示画面
- (void)showUpdateView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    view.center = CGPointMake(self.myStartView.view.bounds.size.width / 2, self.myStartView.view.bounds.size.height / 2);
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.8;
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.center = CGPointMake(view.bounds.size.width / 2, view.bounds.size.height / 3);
    [view addSubview:activityView];
    [activityView startAnimating];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 100, 20)];
    label.text = @"更新文件";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [view addSubview:label];
    
    updateView = view;
    [self.myStartView.view addSubview:view];
    view = nil;
    label = nil;
}

- (void)showRemainViewWithType:(NSUInteger)type
{
    if(remainLabel != nil){
        [remainLabel removeFromSuperview];
    }
    remainLabel = [[UILabel alloc] init];
    if(type == 0){
        [remainLabel setFrame:CGRectMake(0, 0, 180, 20)];
        remainLabel.text = @"通信失败，按键未学习";
    }else{
        [remainLabel setFrame:CGRectMake(0, 0, 80, 20)];
        remainLabel.text = @"通信成功";
    }
    remainLabel.center = CGPointMake([UIScreen mainScreen].bounds.size.width / 2, [UIScreen mainScreen].bounds.size.height / 7 * 6);
    remainLabel.textColor = [UIColor whiteColor];
    remainLabel.textAlignment = NSTextAlignmentCenter;
    remainLabel.backgroundColor = [UIColor blackColor];
    remainLabel.alpha = 0.7;
    remainLabel.layer.cornerRadius = 5.0;
    remainLabel.layer.masksToBounds = YES;
    [self.myViewController.view addSubview:remainLabel];
    remainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(removeRemainView) userInfo:nil repeats:NO];
}

- (void)removeConnectView
{
    [connectTimer invalidate];
    connectTimer = nil;
    [connectView removeFromSuperview];
}

- (void)removeUpdateView
{
    [updateView removeFromSuperview];
}

- (void)removeRemainView
{
    [remainTimer invalidate];
    remainTimer = nil;
    [remainLabel removeFromSuperview];
}

//连接失败
- (void)noConnect
{
    [self removeConnectView];
    //警告视图
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                        message:@"连接失败"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"OK", nil];
    [alertView show];
}

//跳转界面
- (void)skipMainView
{
    [self getJsonDic];
    isUpdata = NO;
    self.window.rootViewController = self.myViewController;
    NSLog(@"%@",@"跳转界面");
    self.myStartView = nil;
}

#pragma mark -- 网络协议
//成功连接服务器
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"连接成功");
    isReConnect = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self removeConnectView];
    });
    //发送主机号
    [asyncSocket writeData:[[CMD_HOST_ID stringByAppendingString:serverID] dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    NSLog(@"%@",@"发送主机ID");
    [asyncSocket readDataWithTimeout:-1 tag:0];
}

//断开连接
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"连接断开");
    if(isReConnect){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showConnectView];
        });
        isReConnect = NO;
        NSLog(@"重新连接");
    }
}

//储存数据到文件中
- (void)saveJsonFile
{
    NSLog(@"%@",@"储存数据");
    //将收到的文件写入mobile2.zip
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:CMD_FILE_NAME];
    [fileManager removeItemAtPath:path error:nil];
    [fileManager createFileAtPath:path contents:jsonData attributes:nil];
    NSLog(@"%@",@"储存完成");
}

//在本地获得json配置文件.zip
- (NSData *)haveJson
{
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:CMD_FILE_NAME];
    NSData *fileData = [NSData dataWithContentsOfFile:path];
    return fileData;
}


//发送消息
- (void)sendMessgae1:(NSString *)message1 message2:(NSString *)message2
{
    if(message1 && message2){
        messagePrefix = message1;
        isSended = YES;
        NSInteger length = [message2 length];
        int x = [[message2 substringWithRange:NSMakeRange(2, length - 2)] intValue];   //读取RA后面的数字
        NSString *message = [NSString stringWithFormat:@"%@%@",message1,[NSString stringWithFormat:@"%d",x]];
        NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
        [asyncSocket writeData:data withTimeout:-1 tag:0];
        NSLog(@"发送消息：%@",message);
    }else{
        NSLog(@"无指令");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showRemainViewWithType:0];
        });
        return ;
    }
}

//发送完整消息
- (void)sendFullMessage:(NSString *)message
{
    NSLog(@"发送完整消息：%@",message);
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    [asyncSocket writeData:data withTimeout:-1 tag:0];
}

//检查收到消息的类型
- (int)checkReceiveMessage:(NSString *)receive
{
    if([receive hasPrefix:CMD_FILE_READ] && ![receive isEqualToString:CMD_FILE_READ_END]){   //接收到要接收文件的大小
        return 3;
    }else if([receive isEqualToString:CMD_FILE_READ_END]){    //接收文件完成
        return 4;
    }else if([receive isEqualToString:CMD_HOST_ID_OK] || [receive isEqualToString:CMD_HOST_ID_ERR]){    //验证主机id
        if([receive isEqualToString:CMD_HOST_ID_OK]){     //验证成功
            return 1;
        }else{
            return 2;
        }
    }else if([receive isEqualToString:CMD_FILE_READ_ERROR]){      //接收文件失败
        return 5;
    }
    return 0;
}

//收到消息
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *receive = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"收到消息%@",receive);
    
    if([self checkReceiveMessage:receive] == 3){   //接收到要接收文件的大小
        fileLength = [[receive substringWithRange:NSMakeRange(10, [receive length] - 10)] intValue];  //设置要接收文件的长度
        [self sendFullMessage:CMD_FILE_READ_START];
        NSLog(@"文件大小为：%d",fileLength);
        NSLog(@"开始接收");
    }else if([self checkReceiveMessage:receive] == 4){    //接收文件完成
        NSLog(@"结束接收");
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_group_t group = dispatch_group_create();  //将数据储存完才能分析数据
        dispatch_group_async(group, queue, ^{
            [self saveJsonFile];
        });
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            [self skipMainView];
            [self removeUpdateView];
        });
    }else if([self checkReceiveMessage:receive] == 5) {
        NSLog(@"%@",@"接收文件失败");
    }else if([receive isEqualToString:[NSString stringWithFormat:@"%@OK\0",messagePrefix]]){
        if(isSended == YES){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showRemainViewWithType:1];
            });
        }
    }else if([receive isEqualToString:@"EVENT-RUN-OK\0"]){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showRemainViewWithType:1];
        });
    }else if([self checkReceiveMessage:receive] == 1 || [self checkReceiveMessage:receive] == 2){    //验证主机id
        if([self checkReceiveMessage:receive] == 1){     //验证成功
            NSLog(@"验证成功");
            NSData *fileData = [self haveJson];
            if(!fileData || isUpdata){          //请求下载配置文件
                if(!fileData){
                    NSLog(@"无文件，请求下载文件");
                }else{
                    NSLog(@"已有文件，请求更新文件");
                }
                [self sendFullMessage:[CMD_FILE_READ_NAME stringByAppendingString:FILE_NAME]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showUpdateView];
                });
            }else{
                NSLog(@"已有文件");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self skipMainView];
                });
            }
        }else{         //验证失败
            NSLog(@"验证失败");
        }
    }else{          //开始接收文件
        NSUInteger len = [jsonData length];    //已接收文件的大小
        NSUInteger dataLen = [data length];    //这次接收数据的大小
        if(len + dataLen <= fileLength){
            [jsonData appendData:data];
            NSLog(@"收到包,大小为：%lu",(unsigned long)data.length);
        }else{
            NSUInteger l = fileLength - len;
            NSData *lastData = [data subdataWithRange:NSMakeRange(0, l)];
            [jsonData appendData:lastData];
            NSData *endData = [data subdataWithRange:NSMakeRange(l, [data length] - l)];
            NSString *endString = [[NSString alloc] initWithData:endData encoding:NSUTF8StringEncoding];
            if([self checkReceiveMessage:endString] == 4){
                NSLog(@"收到包，大小为：%lu,并结束接收",(unsigned long)l);
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_group_t group = dispatch_group_create();  //将数据储存完才能分析数据
                dispatch_group_async(group, queue, ^{
                    [self saveJsonFile];
                });
                dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                    [self skipMainView];
                    [self removeUpdateView];
                });
            }
        }
    }
    [asyncSocket readDataWithTimeout:-1 tag:0];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.window.rootViewController = self.myStartView;
    
    jsonData = [[NSMutableData alloc] init];
    [self.window makeKeyAndVisible];
    return YES;
}


@end
